package com.woyao;

import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.Agreement;
import com.woyao.core.model.ApplyResponse;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Chance;
import com.woyao.core.model.CommentSummary;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetChildHowResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetNextChanceResponse;
import com.woyao.core.model.How;
import com.woyao.core.model.InterestSummary;
import com.woyao.core.model.ItemSummary;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.model.PersonAttr;
import com.woyao.core.model.RelatedChance;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.service.HowService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

//import android.support.v7.app.NotificationCompat;

public class ChanceViewActivity extends AppCompatActivity {


    private Button shareBtn;
    LinearLayout goutongBtn;
    android.support.v7.widget.CardView applyBtn;

    ArrayList<String> howList = new ArrayList<>();

    int yourReportChoice = 0 ;

    String rid = "";
    Integer lastBid = 0;
    Integer partner_id = 0;
    private Chance chance = new Chance();

    private ClipboardManager myClipboard;
    private ClipData myClip;

    private LinearLayoutCompat chanceView;

    private TextView fulltitle;
    private LinearLayout demandPic;
    private LinearLayout demandInfo;
    private LinearLayout pics;
    private LinearLayout orgInfo;
    private LinearLayout managerInfo;
    private LinearLayout agreementsInfo;
    private LinearLayout updatesInfo;
    private LinearLayout explanInfo;
    private LinearLayout attentionInfo;
    private LinearLayout relatedInfo;

    TextView applyText;
    Button messageBtn;

    private Boolean changed = false;

    ProgressDialog progressDialog;

    private ScrollView mainScrollView;

    private Integer COMPLETE_ACCOUNT_CODE = 10;
    private Integer ADD_DEMAND_CODE = 20;
    private Integer COMPLETE_VEFIFY_CODE = 60;   //
    private Integer MYREGISTER_CODE = 4000;

    private Integer REFER_CODE =  917;

    private  ImageView mainImageView;
    private  ImageView markImageView;
    private  ImageView applyImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chance_view_chance);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout

        chanceView = (LinearLayoutCompat) findViewById(R.id.main_detail);
        fulltitle = (TextView) findViewById(R.id.id_fulltitle);
        messageBtn = (Button) findViewById(R.id.chance_msg);
        markImageView  = (ImageView) findViewById(R.id.id_chance_mark_image);
        applyImageView  = (ImageView) findViewById(R.id.id_chance_apply_image);
        LinearLayout markAction = (LinearLayout) findViewById(R.id.id_chance_mark);

        markAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                markIt();
            }
        });

        LinearLayout consultAction = (LinearLayout) findViewById(R.id.id_chance_consult);

        consultAction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                consultIt();
            }
        });

        demandPic = (LinearLayout) findViewById(R.id.demand_pic);
        demandInfo = (LinearLayout) findViewById(R.id.demand_info);
        pics = (LinearLayout) findViewById(R.id.pics);

        applyText = (TextView) findViewById(R.id.id_apply_text);



        orgInfo = (LinearLayout) findViewById(R.id.org_info);
        agreementsInfo = (LinearLayout) findViewById(R.id.agreements_info);

        updatesInfo = (LinearLayout) findViewById(R.id.updates_info);
        managerInfo = (LinearLayout) findViewById(R.id.manager_info);

        explanInfo = (LinearLayout) findViewById(R.id.explan_info);
        attentionInfo = (LinearLayout) findViewById(R.id.attention_info);
        relatedInfo = (LinearLayout) findViewById(R.id.related_info);

        shareBtn = (Button)findViewById(R.id.chance_share);

        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                referIt();
//                displayReferContent();
            }
        });

        goutongBtn = (LinearLayout) findViewById(R.id.id_chance_talk);

        goutongBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadUserBasic();
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }


                if (WoyaoooApplication.displayname.equals("")) {
                    CompleteAccount();
                    return;
                }

                if (WoyaoooApplication.demand_id == 0 ) {
                    AddDemand();
                    return;
                }

                startTalk();
            }
        });

        applyBtn = (android.support.v7.widget.CardView) findViewById(R.id.id_apply);

        applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return ;
                }

                if (chance.getStatus().equals("apply")) {

//                    Intent intent = new Intent();
//                    intent.putExtra("mid", 0);
//                    intent.putExtra("id", chance.getPid());
//                    intent.setClass(ChanceViewActivity.this, RelationActivity.class);
//                    startActivity(intent);
//                    presentDemandChoice();
                    startTalk();
                }else {
                    if (chance.getObject_status().equals("apply")) {
                        applyIt(0,"");
                    } else {
                        if (chance.getDemand_id() ==  0 ) {
                            presentDemandChoice();
                        }else{
                            applyIt(0,"");
//                            confirmApply(0);
                        }
                    }
                }
            }
        });



        LinearLayout reportBtn = (LinearLayout) findViewById(R.id.id_chance_report);


        reportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return ;
                }

                final String[] items =  {"虚假信息","信息有误","分类错误","信息过时","其它"};

                AlertDialog.Builder singleChoiceDialog =
                        new AlertDialog.Builder(ChanceViewActivity.this);
                singleChoiceDialog.setTitle("举报");

                for (String one : items) {
                    // 第二个参数是默认选项，此处设置为0
                    singleChoiceDialog.setSingleChoiceItems(items, yourReportChoice,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    yourReportChoice = which;
                                }
                            });
                }
                singleChoiceDialog.setPositiveButton("确 定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                report(items[yourReportChoice]);
                            }
                        });
                singleChoiceDialog.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                singleChoiceDialog.show();


            }
        });

        LinearLayout smallReferBtn = (LinearLayout) findViewById(R.id.id_detail_refer);

        smallReferBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                referIt();
//                if (!WoyaoooApplication.hasLogin){
//                    Intent intent = new Intent();
//                    intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
//                    startActivityForResult(intent,MYREGISTER_CODE);
//                    return ;
//                }
//                Intent intent = new Intent();
//                intent.putExtra("from", "main");
//                intent.putExtra("mid", chance.getMid());
//                intent.setClass(ChanceViewActivity.this, TalkActivity.class);
//                startActivity(intent);

            }
        });


        mainScrollView = (ScrollView) findViewById(R.id.mainScollView);

        TextView footerText = (TextView) findViewById(R.id.slogan);
        footerText.setText(footerText.getText() + " " + Common.getCurrentVersion(ChanceViewActivity.this));

        Intent intent = getIntent();
        lastBid = intent.getIntExtra("id",0);

        partner_id = intent.getIntExtra("pid",0);

        String from = intent.getStringExtra("from");
        if ( from != null  ) {
            if ( from.equals("main") ) {
                applyBtn.setVisibility(View.GONE);
            }
        }

        getChance( lastBid,partner_id);
//        loadHows();

    }

    private void startTalk(){

        if (chance.getMessage_num() == 0){
            messageBtn.setVisibility(View.GONE);
        }else{
            messageBtn.setVisibility(View.VISIBLE);
            messageBtn.setText( chance.getMessage_num() +"");
        }
        Intent intent = new Intent();
        intent.putExtra("from", "main");
        intent.putExtra("id", chance.getPid());
        intent.putExtra("bid", chance.getId());
        intent.putExtra("type", "match" );
        intent.setClass(ChanceViewActivity.this, TalkActivity.class);
        startActivity(intent);
    }
    private void loadUserBasic(){
        Application application = getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        try {
            WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
            WoyaoooApplication.userId = shared.getInt("userId", 0);
            WoyaoooApplication.displayname = shared.getString("displayname", "");;
            WoyaoooApplication.location = shared.getString("location", "");
            WoyaoooApplication.title = shared.getString("title", "");
            WoyaoooApplication.snailview = shared.getString("snailview", "");
            WoyaoooApplication.demand_id = shared.getInt("demand_id",0);
        }catch (Exception e){

        }

    }
    private void referIt(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }

        Intent intent = new Intent();
        intent.setClass(ChanceViewActivity.this, ReferActivity.class);
        intent.putExtra( "title", chance.getTitle());

        final PersonAttr theManager = chance.getManager();

        intent.putExtra("description", chance.getResourcex() +  "\n " +theManager.getRole() + "\n " + theManager.getLocation() + "\n " +  theManager.getDisplayname() );

        intent.putExtra( "id", chance.getId() );

        mainImageView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(mainImageView.getDrawingCache());
        mainImageView.setDrawingCacheEnabled(false);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 90;
        while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        intent.putExtra("photo_bmp", baos.toByteArray());

        startActivityForResult( intent,REFER_CODE );
    }

    private void report(final String content) {
        progressDialog = new ProgressDialog(ChanceViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("发送消息······");
        progressDialog.show();

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.report(userId,chance.getId(),chance.getPid(),chance.getMid(),content);
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();


                if (response == null){
                    Common.showSnack(ChanceViewActivity.this,fulltitle,"网络错误，请重试");
                    return;
                }
                if (response.isSuccess()) {
                    Common.showSnack(ChanceViewActivity.this,fulltitle,"收到举报");
                } else {
                    Common.alert(ChanceViewActivity.this,response.getMessage());
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }


    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1) {
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        activity.getWindow().setAttributes(lp);
    }

    public  void AddDemand(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(ChanceViewActivity.this, DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }

    public  void CompleteAccount(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(ChanceViewActivity.this, AccountActivity.class);
        startActivityForResult(intent, COMPLETE_ACCOUNT_CODE);
    }

    public  void EditDemand(  ){

        Common.alert(ChanceViewActivity.this,"请完善业务信息，再邀约");
    }

    public void renderVerify(){
        Intent intent = new Intent();
        intent.setClass(ChanceViewActivity.this, VerifyActivity.class);
        startActivityForResult(intent, COMPLETE_VEFIFY_CODE);
    }




    private void displayReferContent() {
        final String text = "Http://www.woyaooo.com/b/" + chance.getId() + "?rid=" + userId;

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("分享").
                setMessage(text).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        myClip = ClipData.newPlainText("text", text);
                        myClipboard.setPrimaryClip(myClip);
                    }
                }).
                create();
        alertDialog.show();
    }



//    @Override
//    public void onBackPressed() {
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        if (drawer.isDrawerOpen(GravityCompat.START)) {
//            drawer.closeDrawer(GravityCompat.START);
//        } else {
//            super.onBackPressed();
//        }
//    }




    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(ChanceViewActivity.this, MoneyActivity.class);
        startActivity(intent);
    }



    private void getChance(final Integer bid, final Integer partner_id) {


        progressDialog = new ProgressDialog(ChanceViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载信息···");
        progressDialog.show();

        AsyncTask<Void, Void, GetNextChanceResponse> task = new AsyncTask<Void, Void, GetNextChanceResponse>() {
            @Override
            protected GetNextChanceResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<GetNextChanceResponse> responseCall = svc.getChance(userId, bid, rid,partner_id);
                rid = "";
                GetNextChanceResponse ret = null;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetNextChanceResponse resp) {
                if (resp != null) {
                    if (resp.isSuccess()) {
                        Chance chance = resp.getContent();
                        if (!resp.getMessage().equals(""))
                            Common.alert(ChanceViewActivity.this, resp.getMessage());

                        if (chance != null) {
                            renderChance(chance);
                            progressDialog.dismiss();
                            return;
                        } else {
                            Common.showSnack(ChanceViewActivity.this, fulltitle, "没有成功获取新机会！");
                        }
                    } else {
                        Common.showSnack(ChanceViewActivity.this, fulltitle, resp.getCondition());
                    }
                } else {
                    Common.showSnack(ChanceViewActivity.this, fulltitle, "请检查网络后重试！");
                }

                lastBid = 0;
                progressDialog.dismiss();


                chance = null;

            }

            @Override
            protected void onCancelled() {

                progressDialog.dismiss();
                Common.showSnack(ChanceViewActivity.this, fulltitle, "没有成功获取新机会！");

            }
        };
        task.execute((Void) null);

    }
//    int yourChoice = 0 ;
//    private void confirmApply( final  Integer demand_id ){
//
//        final String[] items =  (String[])howList.toArray(new String[0]);
//
//        AlertDialog.Builder singleChoiceDialog =
//                new AlertDialog.Builder(ChanceViewActivity.this);
//        singleChoiceDialog.setTitle("希望合作的方式");
//        // 第二个参数是默认选项，此处设置为0
//        singleChoiceDialog.setSingleChoiceItems(items, yourChoice,
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        yourChoice = which;
//                    }
//                });
//        singleChoiceDialog.setPositiveButton("确 定",
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        applyIt( demand_id,items[yourChoice]);
//                    }
//                });
//        singleChoiceDialog.setNegativeButton("取 消",
//                new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                    }
//                });
//        singleChoiceDialog.show();
//    }

    private void loadHows(){
        AsyncTask<Void,Void, GetChildHowResponse> task =
                new AsyncTask<Void, Void, GetChildHowResponse>() {
                    @Override
                    protected GetChildHowResponse doInBackground(Void... params) {
                        HowService svc = ServiceFactory.get(HowService.class);
                        Call<GetChildHowResponse> responseCall = svc.getChildHow("all",WoyaoooApplication.userId,"");
                        try {
                            GetChildHowResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetChildHowResponse response) {

                        ArrayList<How> hows = response.getHowList();
                        howList.clear();
                        for( How hw : hows){
                            howList.add(hw.getName());
                        }
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }


    private void presentDemandChoice( ){
        progressDialog = new ProgressDialog(ChanceViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在处理···");
        progressDialog.show();

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {
                progressDialog.dismiss();
                final List<DemandSummary> demands = response.getContent();

                if (demands.size() ==0 ){
                    new AlertDialog.Builder(ChanceViewActivity.this)
                            .setTitle("信息")
                            .setMessage("说明我的业务")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AddDemand();
                                }
                            }).create().show();
                    return;
                }
                applyIt( demands.get(0).getId(),"");

            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);

    }

    private void applyIt( final Integer demand_id,final String how ) {
        changed = true;
        AsyncTask<Void, Void, ApplyResponse> task =
                new AsyncTask<Void, Void, ApplyResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected ApplyResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<ApplyResponse> responseCall = svc.apply(userId,how, chance.getId(),demand_id  ,chance.getPid(),0);
                        try {
                            ApplyResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ApplyResponse response) {
                        progressDialog.dismiss();
                        if ( response != null) {
                            if (response.isSuccess()) {

                                String msg = response.getMessage();

                                if (response.getMessage().equals("")){
                                    msg = "已经传达了意向";
                                }
                                Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                            setTitle("信息").
                                            setMessage(msg).
                                            setIcon(R.drawable.ic_launcher).
                                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    
                                                }
                                            }).
                                            create();
                                alertDialog.show();
                                
                                try{

                                    Integer pid = Integer.parseInt(  response.getCondition() );
                                    chance.setPid( pid );
                                    chance.setDemand_id(demand_id);
                                    chance.setStatus("apply");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                                applyImageView.setImageResource(R.drawable.shakehand_accent);
                                applyText.setTextColor(ContextCompat.getColor(ChanceViewActivity.this, R.color.red));

//                                startTalk();
//                                if (response.getCondition().equals("relation")) {
//                                    Intent intent = new Intent();
//                                    intent.putExtra("mid", chance.getMid());
//                                    intent.putExtra("id", chance.getPid());
//                                    intent.setClass(ChanceViewActivity.this, RelationActivity.class);
//                                    startActivity(intent);
//                                }

                            }else{
                                if (response.getMessage().equals("")) {
                                    switch (response.getCondition()) {
                                        case "verify":
                                            renderVerify();
                                            break;
                                        case "charge":
                                            renderMoney();
                                            break;
                                        case "personal":
                                            CompleteAccount();
                                            break;
                                        case "demand":
                                            AddDemand();
                                            break;
                                        case "modifydemand":
                                            EditDemand();
                                            break;
                                        default:
                                    }
                                }else{
                                    Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                            setTitle("信息").
                                            setMessage(response.getMessage()).
                                            setIcon(R.drawable.ic_launcher).
                                            setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    switch (response.getCondition()) {
                                                        case "verify":
                                                            renderVerify();
                                                            break;
                                                        case "charge":
                                                            renderMoney();
                                                            break;
                                                        case "personal":
                                                            CompleteAccount();
                                                            break;
                                                        case "demand":
                                                            AddDemand();
                                                            break;
                                                        case "modifydemand":
                                                            EditDemand();
                                                            break;
                                                        default:
                                                    }
                                                }
                                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).
                                            create();
                                    alertDialog.show();
                                }
                            }

                        }else{
                            Toast.makeText(ChanceViewActivity.this,"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }


    private void consultIt(  ) {

        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }


        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.consult(userId,chance.getPid(),chance.getId() );
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {
                            if (response.isSuccess()) {
                                Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                        setTitle("信息").
                                        setMessage(response.getMessage()).
                                        setIcon(R.drawable.ic_launcher).
                                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Integer pid = Integer.parseInt( response.getCondition());
                                                Intent intent = new Intent();
                                                intent.setClass(ChanceViewActivity.this, RelationActivity.class);
                                                intent.putExtra("id", pid);
                                                chance.setPid(pid);
                                                intent.putExtra("mid", chance.getMid());
                                                startActivity(intent);
                                            }
                                        }).
                                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                            }
                                        }).
                                        create();
                                alertDialog.show();
                            }else{
                                Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                        setTitle("信息").
                                        setMessage(response.getMessage()).
                                        setIcon(R.drawable.ic_launcher).
                                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                switch (response.getCondition()) {
                                                    case "verify":
                                                        renderVerify();
                                                        break;
                                                    case "charge":
                                                        renderMoney();
                                                        break;
                                                    default:
                                                }
                                            }
                                        }).
                                        create();
                                alertDialog.show();
                            }

                        }else{
                            Toast.makeText(ChanceViewActivity.this,"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }



    private void markIt(  ) {

        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(ChanceViewActivity.this, RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }
        changed = true;
        chance.setMarked(!chance.getMarked());

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.mark(userId,chance.getPid(),chance.getId() ,chance.getMarked().toString().toLowerCase());
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if ( response != null) {
                            if (response.isSuccess()) {
                                if  (chance.getMarked()){
                                    markImageView.setImageResource(R.drawable.love_accent1);
                                }else{
                                    markImageView.setImageResource(R.drawable.love_empty);
                                }
                            }else{
                                Toast.makeText(ChanceViewActivity.this,response.getMessage(),Toast.LENGTH_SHORT).show();
                                if (response.getCondition().equals("personal")){
                                    CompleteAccount();
                                }
                            }

                        }else{


                            Toast.makeText(ChanceViewActivity.this,"抱歉,处理失败，请重试。",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute((Void) null);

    }


    private void renderChance(final Chance chance) {
        // 不同状态的机会控制背景色？
        chanceView.setVisibility(View.VISIBLE);
//        mainScrollView.setBackgroundColor(ContextCompat.getColor(this, R.color.colorWhite));
        mainScrollView.fullScroll(ScrollView.FOCUS_UP);

        this.chance = chance;
        if (chance == null) {
            return;
        }


        applyText.setText(chance.getApply_text());
        if (chance.getMessage_num() == 0){
            messageBtn.setVisibility(View.GONE);
        }else{
            messageBtn.setVisibility(View.VISIBLE);
            messageBtn.setText( chance.getMessage_num() +"");
        }


//        if (chance.getMessage_num() == 0){
//            chanceMsg.setVisibility(View.GONE);
//        }else{
//            chanceMsg.setVisibility(View.VISIBLE);
//            chanceMsg.setText( chance.getMessage_num() +"");
//        }

        lastBid = chance.getId();

        this.setTitle( chance.getTitle());


        fulltitle.setText(chance.getTitle());


        if (chance.getMarked()){
            markImageView.setImageResource(R.drawable.love_accent1);
        }else{
            markImageView.setImageResource(R.drawable.love_empty);
        }

        if (chance.getStatus().equals("apply")){
            applyImageView.setImageResource(R.drawable.shakehand_accent);
            applyText.setTextColor(ContextCompat.getColor(ChanceViewActivity.this, R.color.colorAccent));
        }else{
            applyImageView.setImageResource(R.drawable.shakehand_white);
            applyText.setTextColor(ContextCompat.getColor(ChanceViewActivity.this, R.color.colorWhite));
        }

        displayDemand();

        displayOrg();

        displayManager();

        displayUpdates();

        displayAgreements();

        displayExplan();

        displayAttention();

        displayRelated();


    }


    private void displayDemand() {

        demandPic.removeAllViews();

        mainImageView = Common.showMainMedia(this, chance.getImage(), demandPic);

        demandInfo.removeAllViews();

//        List<Map<String, String>> businessInfos = new ArrayList<>();
//
//        if (chance.getResourcex() != null && !chance.getResourcex().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源描述");
//                put("info", chance.getResourcex().trim());
//            }});
//        }
//
//        if (chance.getHow() != null && !chance.getHow().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "需求类型");
//                put("info", chance.getHow().trim());
//            }});
//        }
//
//        if (chance.getType() != null && !chance.getType().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "拥有资源");
//                put("info", chance.getType().trim());
//            }});
//        }
//        if (chance.getEnduse() != null && !chance.getEnduse().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源用途");
//                put("info", chance.getEnduse().trim());
//            }});
//        }
//
//        if (chance.getSpecification() != null && !chance.getSpecification().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源规格");
//                put("info", chance.getSpecification().trim());
//            }});
//        }
//        if (chance.getProcessing() != null && !chance.getProcessing().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源经手");
//                put("info", chance.getProcessing().trim());
//            }});
//        }
//        if (chance.getDurable() != null && !chance.getDurable().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源有效");
//                put("info", chance.getDurable().trim());
//            }});
//        }
//        if (chance.getValue() != null && !chance.getValue().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源估值");
//                put("info", chance.getValue().trim());
//            }});
//        }
//        if (chance.getQuantity() > 0 ) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "资源数量");
//                put("info", chance.getQuantity() + "");
//            }});
//        }


//        if (chance.getTypes() != null && !chance.getTypes().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "寻求资源");
//                put("info", chance.getTypes());
//            }});
//        }
//
//
//
//        if (chance.getIntention_fee() > 0 ) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "合作诚意币");
//                put("info", chance.getIntention_fee() + "元");
//            }});
//        }
//
//        if (chance.getRefer_fee()  > 0) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "悬赏介绍");
//                put("info", chance.getRefer_fee() +"元");
//            }});
//        }
//        if (chance.getRequirement() != null && !chance.getRequirement().trim().equals("")) {
//            businessInfos.add(new HashMap<String, String>() {{
//                put("name", "合作要求");
//                put("info", chance.getRequirement().trim());
//            }});
//        }


        for (List<String> info : chance.getAttribs()) {

            LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.list_item, null);

            TextView title = (TextView) item.findViewById(R.id.title);
            TextView text = (TextView) item.findViewById(R.id.text);
            title.setText(info.get(0));
            text.setText(info.get(1));
            demandInfo.addView(item);
        }

//        for (Map.Entry<String, String> entry : chance.getResource().entrySet()) {
//
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//
//            LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.list_item, null);
//
//            TextView title = (TextView) item.findViewById(R.id.title);
//            TextView text = (TextView) item.findViewById(R.id.text);
//            title.setText(entry.getKey() + ":");
//            text.setText(entry.getValue());
//            demandInfo.addView(item);
//        }

        for (Map<String,String> one_item: chance.getRelations()) {
            for (Map.Entry<String, String> entry : one_item.entrySet()) {

                LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.list_item, null);

                TextView title = (TextView) item.findViewById(R.id.title);
                TextView text = (TextView) item.findViewById(R.id.text);
                title.setText(entry.getKey() + ":");
                text.setText(entry.getValue());
                demandInfo.addView(item);
            }
        }

        pics.removeAllViews();


        for (String onepic : chance.getPics()) {
            Common.showMedia(this, onepic, pics);
        }

        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        pics.addView(splitter);
    }

    private void displayOrg() {

        orgInfo.removeAllViews();

        final Map<String, String> theOrg = chance.getOrg();

        if (theOrg.get("id").equals("") || theOrg.get("id").equals("0")  ) {
            orgInfo.setVisibility(View.GONE);
            return;
        }else{
            orgInfo.setVisibility(View.VISIBLE);
        }

        LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
        title1.setText("组织");
        orgInfo.addView(item1);


        LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.partner_item, null);
        CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);
        LinearLayout content = (LinearLayout) item.findViewById(R.id.partner_content);
        content.setVisibility(View.INVISIBLE);

        if (StringUtil.notNullOrEmpty(theOrg.get("logo"))) {
            Picasso.with(this)
                    .load(theOrg.get("logo"))
                    .into(avatar);
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (theOrg.get("id").equals("0")){
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("id",Integer.parseInt(theOrg.get("id")) );
                intent.setClass(ChanceViewActivity.this, OrgViewActivity.class);
                startActivity(intent);
            }
        });
        orgInfo.addView(item);


        List<Map<String, String>> orgList = new ArrayList<>();
        orgList.add(new HashMap<String, String>() {{
            put("name", "名称");
            put("info", theOrg.get("title"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "介绍");
            put("info", theOrg.get("description"));
        }});
        orgList.add(new HashMap<String, String>() {{
            put("name", "行业");
            put("info", theOrg.get("business"));
        }});

        if (!theOrg.get("verify").equals("")) {
            orgList.add(new HashMap<String, String>() {{
                put("name", "认证");
                put("info", theOrg.get("verify"));
            }});
        }
        if (!theOrg.get("member_num").equals("0")) {
            orgList.add(new HashMap<String, String>() {{
                put("name", "成员");
                put("info", theOrg.get("member_num") +"人");
            }});
        }
        if (!theOrg.get("partner_num").equals("0")) {
            orgList.add(new HashMap<String, String>() {{
                put("name", "伙伴");
                put("info", theOrg.get("partner_num")+"人");
            }});
        }

        for (Map<String, String> info : orgList) {
            if (info.get("info").equals(""))
                continue;
            LinearLayout item2 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.list_item, null);
            TextView title = (TextView) item2.findViewById(R.id.title);
            TextView text = (TextView) item2.findViewById(R.id.text);
            title.setText(info.get("name") + "：");
            text.setText(info.get("info"));
            orgInfo.addView(item2);
        }
        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        orgInfo.addView(splitter);
    }

    private void displayManager() {
        managerInfo.removeAllViews();
        final PersonAttr theManager = chance.getManager();

        LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
        title1.setText("联系人");
        managerInfo.addView(item1);

        LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.partner_item, null);
        CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);
        LinearLayout content = (LinearLayout) item.findViewById(R.id.partner_content);
        content.setVisibility(View.INVISIBLE);

        if (StringUtil.notNullOrEmpty(theManager.getSnailview())) {
            Picasso.with(this)
                    .load(theManager.getSnailview())
                    .into(avatar);
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("id",Integer.parseInt( chance.getManager().getId()) );
                intent.setClass(ChanceViewActivity.this, PersonViewActivity.class);
                startActivity(intent);
            }
        });

        managerInfo.addView(item);

        List<Map<String, String>> managersInfolist = new ArrayList<>();


        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "称呼");
            put("info", theManager.getDisplayname());
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "地区");
            put("info", theManager.getLocation());
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "身份");
            put("info", theManager.getRole());
        }});
        managersInfolist.add(new HashMap<String, String>() {{
            put("name", "介绍");
            put("info", theManager.getIntro());
        }});
        if (!theManager.getVerify().equals("")) {
            managersInfolist.add(new HashMap<String, String>() {{
                put("name", "认证");
                put("info", theManager.getVerify());
            }});
        }

        for ( final List<String> theattr : theManager.getAttribs()){
            managersInfolist.add(new HashMap<String, String>() {{
                put("name",theattr.get(0));
                put("info", theattr.get(1));
            }});
        }

        for (Map<String, String> info : managersInfolist) {
            if (info.get("info").equals(""))
                continue;
            LinearLayout item2 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.list_item, null);
            TextView title = (TextView) item2.findViewById(R.id.title);
            TextView text = (TextView) item2.findViewById(R.id.text);
            title.setText(info.get("name") + "：");
            text.setText(info.get("info"));
            managerInfo.addView(item2);
        }

        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        managerInfo.addView(splitter);
    }
    private void voteIt( final Integer uid,final String act ) {

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);

                        Call<BaseResponse> responseCall = svc.addVote(userId, uid,act);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null || response.isSuccess() == false) {
                            Common.showSnack(ChanceViewActivity.this, fulltitle,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.showSnack(ChanceViewActivity.this, fulltitle,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }

    private void displayExplan() {

        explanInfo.removeAllViews();

        final ItemSummary explan = chance.getExplan();

        if (chance.getExplan().getId() == 0) {
            explanInfo.setVisibility(View.GONE);
            return;
        }else{
            explanInfo.setVisibility(View.VISIBLE);
        }

        LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
        title1.setText("说明");
        explanInfo.addView(item1);

        LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.explan_item, null);
        CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);
        TextView title = (TextView) item.findViewById(R.id.partner_title);
        final TextView desc = (TextView) item.findViewById(R.id.partner_desc);
        title.setText(explan.getTitle());
        desc.setText(explan.getDescription());

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               loadAdvice(chance.getPid(),chance.getMid(),desc);

//                Intent intent = new Intent();
//                intent.setClass(ChanceViewActivity.this, WebviewActivity.class);
//                intent.putExtra("title", "隐私政策 ");
//                intent.putExtra("link", "https://woyaooo.com/solution/" + explan.getId());
//                startActivity(intent);
            }
        });

        if (StringUtil.notNullOrEmpty( explan.getSnailview())) {
            Picasso.with(this)
                    .load(explan.getSnailview())
                    .into(avatar);
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }
        explanInfo.addView(item);


        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        explanInfo.addView(splitter);
    }

    private void displayAttention() {

        attentionInfo.removeAllViews();
        final ItemSummary attention = chance.getAttention();

        if (chance.getAttention().getId() == 0) {
            attentionInfo.setVisibility(View.GONE);
            return;
        }else{
            attentionInfo.setVisibility(View.VISIBLE);
        }

        LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
        TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
        title1.setText("提示");
        attentionInfo.addView(item1);


        LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.explan_item, null);
        CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);
        TextView title = (TextView) item.findViewById(R.id.partner_title);
        TextView desc = (TextView) item.findViewById(R.id.partner_desc);
        title.setText(attention.getTitle());
        desc.setText(attention.getDescription());

        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(ChanceViewActivity.this, WebviewActivity.class);
                intent.putExtra("title", "隐私政策 ");
                intent.putExtra("link", "https://woyaooo.com/privacy.html");
                startActivity(intent);
            }
        });

        if (StringUtil.notNullOrEmpty( attention.getSnailview())) {
            Picasso.with(this)
                    .load(attention.getSnailview())
                    .into(avatar);
        } else {
            avatar.setImageResource(R.drawable.no_avartar);
        }
        attentionInfo.addView(item);


        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        attentionInfo.addView(splitter);
    }

    private void displayRelated() {

        relatedInfo.removeAllViews();

        if (chance.getRelated().size() == 0)
            return;

        if (!chance.getRelated_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(chance.getRelated_summary());
            relatedInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(chance.getRelated())) {
            //合作的人
            Integer order = 0;
            for (final RelatedChance rc : chance.getRelated()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.related_item, null);
                final TextView ordertxt = (TextView) item.findViewById(R.id.related_order);
                final TextView title = (TextView) item.findViewById(R.id.related_title);
                final CircleImageView img = (CircleImageView) item.findViewById(R.id.related_image);
                LinearLayout content = (LinearLayout) item.findViewById(R.id.related_content);
                final TextView descr = (TextView) item.findViewById(R.id.related_desc);
                ordertxt.setText(order +"");
                title.setText(rc.getTitle());
                descr.setText(rc.getDescription());

                if (StringUtil.notNullOrEmpty(rc.getImage())) {
                    Picasso.with(ChanceViewActivity.this)
                            .load(rc.getImage())
                            .into(img);
                } else {
                    img.setImageResource(R.drawable.no_avartar);
                }
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id", rc.getId());
                        intent.setClass(ChanceViewActivity.this, ChanceViewActivity.class);
                        startActivity(intent);
                    }
                });


                relatedInfo.addView(item);

            }
        }

        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        relatedInfo.addView(splitter);
    }

    private void displayUpdates() {

        updatesInfo.removeAllViews();

        if (chance.getMoves().size() == 0)
            return;

        if (!chance.getMoves_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(chance.getMoves_summary());
            updatesInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(chance.getMoves())) {
            //合作的人
            Integer order = 0;
            for (final InterestSummary interest : chance.getMoves()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.move_item, null);
                final TextView move_order = (TextView) item.findViewById(R.id.move_order);
                final TextView move_subject = (TextView) item.findViewById(R.id.move_subject);
                final TextView move_desc = (TextView) item.findViewById(R.id.move_desc);
                final TextView move_created = (TextView) item.findViewById(R.id.move_created);
                final TextView yes_dig_num = (TextView) item.findViewById(R.id.yes_dig_num);
                final TextView no_dig_num = (TextView) item.findViewById(R.id.no_dig_num);
                final LinearLayout mediaItems = (LinearLayout) item.findViewById(R.id.id_move_medias);
                final ImageView voteUp = (ImageView) item.findViewById(R.id.yesdig);
                final ImageView voteDown = (ImageView) item.findViewById(R.id.nodig);
                final TextView move_displayname = (TextView) item.findViewById(R.id.move_displayname);
                final CircleImageView move_avatar = (CircleImageView) item.findViewById(R.id.move_avatar);

                final LinearLayout moveItem = (LinearLayout) item.findViewById(R.id.moveItem);
                final TextView move_title = (TextView) item.findViewById(R.id.move_title);
                move_title.setText( interest.getTitle());

                moveItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (interest.getRelation_type().equals("demand")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(ChanceViewActivity.this, ChanceViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("org")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(ChanceViewActivity.this, OrgViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("person")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getUser_id());
                            intent.setClass(ChanceViewActivity.this, PersonViewActivity.class);
                            startActivity(intent);
                        }
                    }
                });

                move_displayname.setText(interest.getDisplayname());

                if (StringUtil.notNullOrEmpty(interest.getSnailview())) {
                    Picasso.with(ChanceViewActivity.this)
                            .load(interest.getSnailview())
                            .into(move_avatar);
                } else {
                    move_avatar.setImageResource(R.drawable.no_avartar);
                }
                move_avatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getUser_id());
                        intent.setClass(ChanceViewActivity.this, PersonViewActivity.class);
                        startActivity(intent);
                    }
                });

                move_order.setText( order  + "" );

                voteUp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        yes_dig_num.setText( interest.getPositive() + 1 +"");
                        voteIt( interest.getId(), "up");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                voteDown.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        no_dig_num.setText( interest.getNegative() + 1 +"");
                        voteIt( interest.getId(), "down");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                if  (interest.getVoted()){
                    voteUp.setImageResource(R.drawable.vote_up_grey);
                    voteDown.setImageResource(R.drawable.vote_down_grey);
                }
                move_desc.setText(interest.getDescription());
                move_created.setText(interest.getCreated());
                yes_dig_num.setText(interest.getPositive() +"");
                no_dig_num.setText(interest.getNegative() +"");

                String tempstr = "";
                for (String onestr : interest.getSubject()){
                    tempstr += "#" + onestr +" ";
                }
                move_subject.setText( tempstr ) ;

                for (final MediaSummary ms : interest.getMedias()) {
                    android.support.v7.widget.ContentFrameLayout image_item = (android.support.v7.widget.ContentFrameLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.media_item, null);
                    ImageView imageView = (ImageView) image_item.findViewById(R.id.media_pic);
                    final Button deleteBtn = (Button)image_item.findViewById(R.id.media_delete);
                    final Button playBtn = (Button)image_item.findViewById(R.id.media_play);

                    if (ms.getId().endsWith("mp4")){
                        playBtn.setVisibility(View.VISIBLE);
                    }else{
                        playBtn.setVisibility(View.GONE);
                    }

                    deleteBtn.setVisibility(View.GONE);

                    if (StringUtil.notNullOrEmpty(ms.getSnailview())) {
                        Picasso.with(ChanceViewActivity.this)
                                .load(ms.getSnailview())
                                .into(imageView);
                    } else {
                        imageView.setImageResource(R.drawable.no_avartar);
                    }

                    mediaItems.addView(image_item);

                }

                updatesInfo.addView(item);

            }
        }

        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        updatesInfo.addView(splitter);
    }

    private void displayAgreements() {

        agreementsInfo.removeAllViews();

        if (chance.getAgreements().size() == 0)
            return;

        if (!chance.getAgreements_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(chance.getAgreements_summary());
            agreementsInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(chance.getAgreements())) {
            //合作的人
            Integer order = 0;
            for (final Agreement agreement : chance.getAgreements()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.agreement_item, null);
                CircleImageView agreement_avatar = (CircleImageView) item.findViewById(R.id.agreement_avatar);
                final TextView agreement_title = (TextView) item.findViewById(R.id.agreement_title);
                final TextView agreement_desc = (TextView) item.findViewById(R.id.agreement_desc);
                final TextView agreement_order = (TextView) item.findViewById(R.id.agreement_order);

                agreement_title.setText(agreement.getTitle());
                agreement_desc.setText(agreement.getDescription());
                agreement_order.setText(order + "");

                if (StringUtil.notNullOrEmpty(agreement.getImage())) {
                    Picasso.with(ChanceViewActivity.this)
                            .load(agreement.getImage())
                            .into(agreement_avatar);
                } else {
                    agreement_avatar.setImageResource(R.drawable.no_avartar);
                }

                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id",agreement.getRelation_demand_id() );
                        intent.setClass(ChanceViewActivity.this, ChanceViewActivity.class);
                        startActivity(intent);
                    }
                });

                for (final CommentSummary comment : agreement.getComments()) {
                    LinearLayout comment_item = (LinearLayout) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.agreement_comment_item, null);
                    CircleImageView comment_avatar = (CircleImageView) comment_item.findViewById(R.id.comment_avatar);
                    final TextView commentDisplayname = (TextView) comment_item.findViewById(R.id.comment_displayname);
                    final TextView commentTitle = (TextView) comment_item.findViewById(R.id.comment_title);
                    final TextView commentDesc = (TextView) comment_item.findViewById(R.id.comment_desc);
                    final TextView commentRate = (TextView) comment_item.findViewById(R.id.comment_rate);
                    final TextView commentCharge = (TextView) comment_item.findViewById(R.id.comment_charge);
                    final Button viewComment = (Button)comment_item.findViewById(R.id.id_view_comment);
                    final ImageView yesDig = (ImageView) comment_item.findViewById(R.id.yesdig);
                    final ImageView noDig = (ImageView) comment_item.findViewById(R.id.nodig);
                    final TextView dig = (TextView) comment_item.findViewById(R.id.comment_dig);

                    if (comment.getCharge() >0 ) {
                        viewComment.setVisibility(View.VISIBLE);
                        commentCharge.setVisibility(View.VISIBLE);
                        commentCharge.setText( "￥" + comment.getCharge() );
                    }else{
                        viewComment.setVisibility(View.GONE);
                        commentCharge.setVisibility(View.GONE);
                    }


                    commentDesc.setText(comment.getDescription());
                    commentTitle.setText(comment.getTitle());
                    commentDisplayname.setText(comment.getDisplayname());

                    String rateStr = "";
                    for ( int i = 0; i < comment.getRate();i++ ){
                        rateStr = rateStr  +"★";
                    }
                    if (comment.getRate()> 0) {
                        commentRate.setText( rateStr);
                    }else{
                        commentRate.setText("" );
                    }

                    if ( comment.getDiggable() ){
                        yesDig.setVisibility(View.VISIBLE);
                        noDig.setVisibility(View.GONE);
                    }else{
                        yesDig.setVisibility(View.GONE);
                        noDig.setVisibility(View.VISIBLE);
                    }
                    dig.setText(comment.getDig() +"");

                    yesDig.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (comment.getDiggable()) {
                                yesDig.setVisibility(View.GONE);
                                noDig.setVisibility(View.VISIBLE);
                                dig.setText((Integer.parseInt(dig.getText().toString()) + 1) + "");
                                digIt(comment.getId());
                            }
                        }
                    });

                    if (StringUtil.notNullOrEmpty(comment.getSnailview())) {
                        Picasso.with(ChanceViewActivity.this)
                                .load(comment.getSnailview())
                                .into(comment_avatar);
                    } else {
                        comment_avatar.setImageResource(R.drawable.no_avartar);
                    }

                    comment_avatar.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.putExtra("id",comment.getUser_id() );
                            intent.setClass(ChanceViewActivity.this, PersonViewActivity.class);
                            startActivity(intent);
                        }
                    });

                    viewComment.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                    setTitle("信息").
                                    setMessage("将收取" + comment.getCharge() + "元").
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            loadComment(comment.getId(),commentDesc);
                                        }
                                    }).
                                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                        }
                    });

                    item.addView(comment_item);
                    View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.light_splitter, null);
                    item.addView(splitter);
                }

                agreementsInfo.addView(item);
                if (order < chance.getAgreements().size()) {
                    View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.light_splitter, null);
                    agreementsInfo.addView(splitter);
                }
            }
        }

        View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.splitter, null);
        agreementsInfo.addView(splitter);
    }

    private void digIt( final Integer comment_id ) {

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    boolean bizComplete = false;

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<BaseResponse> responseCall = svc.dig(userId, comment_id);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null || response.isSuccess() == false) {
                            Common.showSnack(ChanceViewActivity.this, fulltitle,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.showSnack(ChanceViewActivity.this, fulltitle,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }




    private  void loadAdvice(final Integer pid,final Integer mid,final TextView descTxt){
        progressDialog = new ProgressDialog(ChanceViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在加载信息······");
        progressDialog.show();
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.getAdvice(WoyaoooApplication.userId,mid,pid);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
                if (response != null) {

                    if (response.isSuccess()) {
                        descTxt.setText(response.getMessage());
                        descTxt.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                    }else{
                        Dialog alertDialog = new AlertDialog.Builder(ChanceViewActivity.this).
                                setTitle("信息").
                                setMessage(response.getMessage()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (response.getCondition().equals("charge")){
                                            renderMoney();
                                        }
                                    }
                                }).
                                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                        alertDialog.show();


                    }
//                    Common.alert( ChanceActivity.this,response.getMessage());
                } else {
                    Common.alert( ChanceViewActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }





    private  void loadComment(final Integer comment_id,final TextView descTxt){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.getCommentContent(WoyaoooApplication.userId,comment_id);
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {

                    if (response.isSuccess()) {
                        descTxt.setText(response.getMessage());
                        descTxt.setTextColor(getResources().getColor(R.color.red));
                        Toast.makeText(ChanceViewActivity.this,"请查看收费评论",Toast.LENGTH_LONG);
                    }else{
                        Common.alert( ChanceViewActivity.this,response.getMessage());
                        if (response.getCondition().equals("charge")){
                            renderMoney();
                        }
                    }
//                    Common.alert( ChanceActivity.this,response.getMessage());
                } else {
                    Common.alert( ChanceViewActivity.this,"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if  (requestCode == COMPLETE_ACCOUNT_CODE ){
            String displayName = data.getStringExtra("displayname");
         

        }

        if  (requestCode == ADD_DEMAND_CODE  ) {   //add or change demand
            Integer demand_id = data.getIntExtra("demand_id", 0);
            applyIt(demand_id,"");
        
        }

        if  (requestCode == COMPLETE_ACCOUNT_CODE && resultCode ==666 ){
            String displayName = data.getStringExtra("displayname");

        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            intent.putExtra("changed", changed );
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(0, intent);
        finish();
        return true;
    }
}
